package com.jasper.dagger2learn.base.view

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView

abstract class BaseFragment : Fragment(), MvpView {
    var mainView: View? = null
    private var loadingDialog: BasePopupView? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (mainView != null) {
            return mainView
        } else {
            return if (getLayoutId() != 0) {
                mainView = inflater.inflate(getLayoutId(), container, false)
                mainView
            } else {
                mainView = super.onCreateView(inflater, container, savedInstanceState)
                mainView
            }
        }

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
        initEvent()
    }

    abstract fun getLayoutId(): Int

    abstract fun initData()

    abstract fun initView()

    abstract fun initEvent()

    private fun initLoadingView() {
        loadingDialog = XPopup.Builder(requireContext()).asLoading("请稍候...").show()
    }

    private fun showLoadingView() {
        if (null != loadingDialog) {
            loadingDialog!!.show()
        } else {
            initLoadingView()
            loadingDialog!!.show()
        }
    }

    private fun hideLoadingView() {
        if (null != loadingDialog && loadingDialog!!.isShow) {
            loadingDialog!!.dismiss()
        }
    }

    /**
     * 将显示dialog和取消dialog放在了基础类中
     */
    override fun showLoading() {
        showLoadingView()
    }

    override fun hideLoading() {
        hideLoadingView()
    }

    override fun onDestroy() {
        super.onDestroy()
        super.onDestroy()

        // 销毁dialog
        if (null != loadingDialog && loadingDialog!!.isShow) {
            loadingDialog!!.dismiss()
        }
        loadingDialog = null
    }
}